
var user = $('#user'),
    userAdd = $('#user-add'),
    userEdit = $('#user-edit'),
    userAddAccounts = $('#user-add-accounts'),
    userAddPassword = $('#user-add-password'),
    userAddStaffName = $('#user-add-staff-name'),

    userEditAccounts = $('#user-edit-accounts'),
    userEditStaffName = $('#user-edit-staff-name'),
    userEditPassword = $('#user-edit-password'),
    userEditStateButton = $('#user-edit-state-button'),
    userEditState = $('#user-edit-state'),
    userEditId = $('#user-edit-id'),

    userSearchKeywords = $('#user-search-keywords'),
    userSearchDateType = $('#user-search-date-type'),
    userSearchDateFrom = $('#user-search-date-from'),
    userSearchDateTo = $('#user-search-date-to'),
    userSearchState = $('#user-search-state'),
    userTool = $('#user-tool'),
    randAdd = $('.rand-add'),
    randEdit = $('.rand-edit'),
    userDate,
    getRandPassword,
    userOpt,
    userAccounts;
//


//获取数据
user.datagrid({
    url: ThinkPHP['MODULE'] + '/User/getList',
    fit: true,
    fitColumns: true,
    border: false,
    rownumbers: true,
    pagination: true,
    striped : true,
    pageSize:10,
    pageNumber:1,
    pageList:[10,20,30,40,50],
    sortName: 'create_time',
    sortOrder: 'DESC',
    toolbar: '#user-tool',
    columns: [[
        {
            field: 'id',
            title: '自动编号',
            width: 100,
            checkbox: true,
        },
        {
            field: 'accounts',
            title: '帐号名称',
            width: 100,
        },
        {
            field: 'staff_name',
            title: '关联档案姓名',
            width: 100,
        },
        {
            field: 'last_login_time',
            title: '登录时间',
            width: 100,
            sortable: true,
        },
        {
            field: 'last_login_ip',
            title: '登录IP',
            width: 100,
        },
        {
            field: 'login_count',
            title: '登录次数',
            width: 80,
            sortable: true,
        },
        {
            field: 'create_time',
            title: '创建时间',
            width: 100,
            sortable: true,

        },
        {
            field: 'state',
            title: '状态',
            width: 60,
            fixed: true,
            formatter: function (value,row) {

                var state = '';
                switch (value) {
                    case '正常':
                        state = '<a href="javascript:void(0);" class="user_state user_state_1" user_id="' + row.id + '" user_state="正常" style="height:18px;margin-left: 11px;"></a>';
                        break;
                    case '冻结':
                        state = '<a href="javascript:void(0);" class="user_state user_state_2" user_id="' + row.id + '" user_state="冻结" style="height:18px;margin-left: 11px;"></a>';
                        break;
                }
                return state;
            }
        },
    ]],
    onLoadSuccess: function () {
        $('.user_state_1').linkbutton({
            iconCls: 'icon-ok',
            plain: true,
        });
        $('.user_state_2').linkbutton({
            iconCls: 'icon-lock',
            plain: true,
        });
        //单击修改状态
        $('.user_state').click(function () {
            var id = $(this).attr('user_id');
            var state = $(this).attr('user_state');
            switch (state) {
                case '正常':
                    $.messager.confirm('修改状态提示','真的要冻结此帐号吗？',function (flag) {
                        if (flag) {
                            $.ajax({
                                url: ThinkPHP['MODULE'] +　'/User/state',
                                type: 'POST',
                                data: {
                                    'id': id,
                                    'state': '冻结'
                                },
                                beforeSend: function () {
                                    $.messager.progress({
                                        'text': '正在冻结帐号...'
                                    });
                                },
                                success: function (data) {
                                    $.messager.progress('close');
                                    if(data > 0) {
                                        $.messager.show({
                                            title: '冻结提示',
                                            msg: '冻结帐号成功'
                                        });
                                        user.datagrid('reload');
                                    }

                                }
                            });
                        }
                    });
                    break;
                case '冻结':
                    $.messager.confirm('修改状态提示','真的要审核通过帐号吗？',function (flag) {
                        if (flag) {
                            $.ajax({
                                url: ThinkPHP['MODULE'] +　'/User/state',
                                type: 'POST',
                                data: {
                                    'id': id,
                                    'state': '正常'
                                },
                                beforeSend: function () {
                                    $.messager.progress({
                                        'text': '正在审核通过帐号...'
                                    });
                                },
                                success: function (data) {
                                    $.messager.progress('close');
                                    if(data > 0) {
                                        $.messager.show({
                                            title: '审核通过提示',
                                            msg: '审核通过帐号成功'
                                        });
                                        user.datagrid('reload');
                                    }

                                }
                            });
                        }
                    });
                    break;
            }
        });
    }
});




//工具条操作
userOpt = {
    add: function () {
        userAdd.dialog('open');
        //关联 档案姓名  点击 新增时再加载
        userAddStaffName.combogrid({
            width: 120,
            height:32,
            panelWidth: 450,
            panelHeight: 'auto',
            panelMaxHeight: 227,
            striped : true,
            fitColumns: true,
            border: false,
            url: ThinkPHP['MODULE'] + '/Staff/getNotRelationList',
            rownumbers: true,
            idField: 'id',
            textField: 'name',
            pagination: true,
            editable: false,
            pageSize:10,
            pageNumber:1,
            pageList:[10,20,30,40,50],
            sortName: 'create_time',
            sortOrder: 'DESC',
            columns: [[
                {
                    field: 'id',
                    title: '自动编号',
                    width: 50,
                    hidden: true,
                },
                {
                    field: 'name',
                    title: '姓名',
                    width: 80,
                },
                {
                    field: 'number',
                    title: '工号',
                    width: 50,
                    sortable: true,
                },
                {
                    field: 'gender',
                    title: '性别',
                    width: 50,
                    sortable: true,
                },
                {
                    field: 'id_card',
                    title: '身份证',
                    width: 150,
                },
                {
                    field : 'post',
                    title : '职位',
                    width : 50
                },
                {
                    field : 'create_time',
                    title : '创建时间',
                    width : 100,
                    hidden: true
                }]],
            onOpen: function () {
                //当打开时 重新加载 下拉表格
                userAddStaffName.combogrid('grid').datagrid('reload');
            },
            onShowPanel:function () {
                //当显示面板时 重新加载 下拉表格的宽度
                userAddStaffName.combogrid('panel').panel('resize',{
                    width: '450px',
                })
            }
        });
    },
    edit: function () {
        //关联 档案姓名  点击 新增时再加载
        userEditStaffName.combogrid({
            width: 120,
            height:32,
            panelWidth: 450,
            panelHeight: 'auto',
            panelMaxHeight: 227,
            striped : true,
            fitColumns: true,
            border: false,
            url: ThinkPHP['MODULE'] + '/Staff/getNotRelationList',
            rownumbers: true,
            idField: 'id',
            textField: 'name',
            pagination: true,
            editable: false,
            pageSize:10,
            pageNumber:1,
            pageList:[10,20,30,40,50],
            sortName: 'create_time',
            sortOrder: 'DESC',
            columns: [[
                {
                    field: 'id',
                    title: '自动编号',
                    width: 50,
                    hidden: true,
                },
                {
                    field: 'name',
                    title: '姓名',
                    width: 80,
                },
                {
                    field: 'number',
                    title: '工号',
                    width: 50,
                    sortable: true,
                },
                {
                    field: 'gender',
                    title: '性别',
                    width: 50,
                    sortable: true,
                },
                {
                    field: 'id_card',
                    title: '身份证',
                    width: 150,
                },
                {
                    field : 'post',
                    title : '职位',
                    width : 50
                },
                {
                    field : 'create_time',
                    title : '创建时间',
                    width : 100,
                    hidden: true
                }]],
            onOpen: function () {
                //当打开时 重新加载 下拉表格
                userEditStaffName.combogrid('grid').datagrid('reload');
            },
            onShowPanel:function () {
                //当显示面板时 重新加载 下拉表格的宽度
                userEditStaffName.combogrid('panel').panel('resize',{
                    width: '450px',
                })
            }
        });
        var rows = user.datagrid('getSelections');
        if (rows.length == 1) {
            userEdit.dialog('open');
            $.ajax({
                url: ThinkPHP['MODULE'] + '/User/getOne',
                type: 'POST',
                data: {
                    'id': rows[0].id
                },
                beforeSend:function () {
                    $.messager.progress({'text':'正在获取数据...'});
                },
                success: function (data) {
                    $.messager.progress('close');
                    if (data) {
                        userEdit.form('load',{
                           'id' : data.id,
                           'accounts' :data.accounts,
                           'staff_name' :data.staff_name,

                        })

                        userEditAccounts.textbox('textbox').select();

                        if (data.state == '正常') {
                            userEditStateButton.switchbutton('check');
                        } else {
                            userEditStateButton.switchbutton('uncheck');
                        }


                    } else {
                        $.messager.alert('操作警告', '没有获取到相应数据', 'warning');
                    }
                }
            });


        } else {
            $.messager.alert('编辑操作', '编辑记录只能选择一条数据', 'warning');
        }
    },
    remove: function () {
        var rows = user.datagrid('getSelections');
        var ids = [];
        if (rows.length > 0) {
            for(var i=0; i<rows.length; i++){
                ids.push(rows[i].id);
            }

            $.messager.confirm('删除操作', '你真的要删除 '+ rows.length + '条数据吗？',function (flag) {
                if(flag) {
                    $.ajax({
                        url: ThinkPHP['MODULE'] +　'/User/remove',
                        type: 'POST',
                        data: {
                            'ids' : ids.join(','),
                        },
                        beforeSend: function () {
                            user.datagrid('loading');
                        },
                        success: function (data) {
                            user.datagrid('loaded');
                            if (data) {
                                user.datagrid('reload');
                                $.messager.show({
                                    title: '删除提示',
                                    msg : '删除' + data + '条数据'
                                });
                            } else {
                                $.messager.alert('删除提示','没有任何数据被删除','warning');
                            }


                        }
                    });
                }
            });

        } else {
            $.messager.alert('编辑操作', '删除记录至少选择一条数据', 'warning');
        }

    },
    reload: function () {
        user.datagrid('reload');
    },
    redo: function () {
        user.datagrid('unselectAll');
    },
    search: function () {
        if (userTool.form('validate')) {
            user.datagrid('load', {
                keywords: userSearchKeywords.textbox('getValue'),
                dateType: userSearchDateType.combobox('getValue'),
                dateFrom: userSearchDateFrom.textbox('getValue'),
                dateTo: userSearchDateTo.textbox('getValue'),
                state: userSearchState.combobox('getValue'),
            });
        } else {
            userSearchDateType.combobox('showPanel')
        }
    },
    reset: function () {
        userSearchKeywords.textbox('clear');
        userSearchDateType.combobox('clear').combobox('disableValidation');
        userSearchState.combobox('clear');
        userSearchDateFrom.datebox('clear');
        userSearchDateTo.datebox('clear');
        user.datagrid('sort',{
            sortAccounts: 'create_time',
            sortOrder: 'DESC'
        });
        this.search();
    }
}
/***********************新增-编辑********************/
//新增对话框
userAdd.dialog({
    title: '帐号新增',
    width: 400,
    height:260,
    closed: true,
    iconCls:'icon-add',
    modal:true,
    maximizable:true,
    buttons:[{
        text:'保存',
        size:'large',
        iconCls:'icon-accept',
        handler:function(){
            if (userAdd.form('validate')) {
                $.ajax({
                    url: ThinkPHP['MODULE'] + '/User/register',
                    type: 'POST',
                    data: {
                        'accounts': userAddAccounts.val(),
                        'password': userAddPassword.val(),
                        'staff_id': userAddStaffName.combogrid('getValue'),
                        'staff_name': userAddStaffName.combogrid('getText'),

                    },
                    beforeSend: function () {
                        $.messager.progress({
                            'text': '正在处理中...'
                        });
                    },
                    success: function (data) {
                        $.messager.progress('close');
                        if (data > 0) {
                            $.messager.show({
                                title: '操作提示',
                                  msg: '添加成功'
                            });
                            userAdd.dialog('close');
                            user.datagrid('load');
                        } else if (data == -1) {
                            $.messager.alert('添加操作', '帐号名称被占用', 'warning', function () {
                                userAddAccounts.textbox('textbox').select();
                            });
                        }
                    }
                });
            }

        }
    },{
        text:'取消',
        size:'large',
        iconCls:'icon-cross',
        handler:function(){
            userAdd.dialog('close');
        }
    }],
    onClose: function () {
        userAdd.form('reset');
        userAdd.dialog('center');
    }



});

//编辑对话框
userEdit.dialog({
    title: '帐号编辑',
    width: 400,
    height:300,
    closed: true,
    iconCls:'icon-edit',
    modal:true,
    maximizable:true,
    buttons:[{
        text:'保存',
        size:'large',
        iconCls:'icon-accept',
        handler:function(){
            if (userEdit.form('validate')) {
                $.ajax({
                    url: ThinkPHP['MODULE'] + '/User/update',
                    type: 'POST',
                    data: {
                        'id': userEditId.val(),
                        'password': userEditPassword.val(),
                        'notpassword': userEditPassword.val(),
                        'state': userEditState.val(),
                        'staff_id': userEditStaffName.combogrid('getValue'),
                        'staff_name': userEditStaffName.combogrid('getText'),
                    },
                    beforeSend: function () {
                        $.messager.progress({
                            'text': '正在处理中...'
                        });
                    },
                    success: function (data) {
                        $.messager.progress('close');
                        if (data > 0) {
                            $.messager.show({
                                title: '操作提示',
                                msg: '修改成功'
                            });
                            userEdit.dialog('close');
                            user.datagrid('reload');
                        } else if (data == -1) {
                            $.messager.alert('修改操作', '帐号名称被占用', 'warning', function () {
                                userEditAccounts.textbox('textbox').select();
                            });
                        } else if(data == 0) {
                            $.messager.alert('修改操作', '尚未修改字段或未知错误', 'warning', function () {
                                userEditAccounts.textbox('textbox').select();
                            });
                        }
                    }
                });
            }
        }
    },{
        text:'取消',
        size:'large',
        iconCls:'icon-cross',
        handler:function(){
            userEdit.dialog('close');
        }
    }],
    onClose: function () {
        userEdit.form('reset');
        userEdit.dialog('center');
    }



});

/***********************新增-编辑********************/
userAccounts = {
    width: 220,
    height: 32,
    required: true,
    disabled: true,
    validType: 'length[2,20]',
    missingMessage: '请输入帐号名称',
    invalidMessage: '帐号名称2到20位'
}

//编辑帐号
userEditAccounts.textbox(userAccounts);
userAddPassword.textbox({
    width:220,
    height:32,
    validType:'length[6,30]',
    required: true,
    missingMessage:'请输入帐号密码',
    invalidMessage:'帐号密码6到30位'
});
userEditPassword.textbox({
    width:220,
    height:32,
    validType:'length[6,30]',
    missingMessage:'请输入帐号密码',
    invalidMessage:'帐号密码6到30位'
});
//新增帐号
userAccounts.disabled = false,
userAddAccounts.textbox(userAccounts);
userAddPassword.textbox({
    width:220,
    height:32,
    required:true,
    validType:'length[6,30]',
    missingMessage:'请输入帐号密码',
    invalidMessage:'帐号密码6到30位'
});
//随机密码生成器
randAdd.click(function () {
    userAddPassword.textbox('setValue',getRandPassword(8,16));
});
randEdit.click(function () {
    userEditPassword.textbox('setValue',getRandPassword(8,16));
});
//随机密码生成器
getRandPassword = function (min,max) {
    var soure = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    var length = Math.ceil( Math.random() * (max-min) + min );
    var password = '';
    for (var i = 0; i<length; i++) {
        password += soure.charAt(Math.ceil(Math.random()*1000 % soure.length));
    }

    return password;

}
//修改状态
userEditStateButton.switchbutton({
   width: 65,
    onText: '正常',
    offText: '冻结',
    onChange: function (checked) {
        if (checked) {
            userEditState.val('正常');
        } else {
            userEditState.val('冻结');
        }
    }
})

/***********************新增-编辑********************/



/***********************查询区域********************/
userSearchKeywords.textbox({
    width: 150,
    prompt: '帐号'
});

//时间类型
userSearchDateType.combobox({
    width: 100,
    editable: false,
    prompt: '时间类型',
    data: [{
       id: 'create_time',
       text: '创建时间'
    }],
    valueField: 'id',
    textField: 'text',
    required: true,
    novalidate: true,
    panelHeight: 'auto',
    tipPosition : 'left',
    missingMessage : '请选择时间类型'
})

//状态类型
userSearchState.combobox({
    width: 70,
    editable: false,
    prompt: '状态',
    data: [{
        id: '正常',
        text: '正常'
    },
    {
        id: '冻结',
        text: '冻结'
    }],
    valueField: 'id',
    textField: 'text',
    panelHeight: 'auto',
})

//查询时间对象
userDate = {
    width: 100,
    editable: false,
    onSelect:function () {
        if (userSearchDateType.combobox('enableValidation').combobox('isValid') == false) {
            userSearchDateType.combobox('showPanel');
        }
    }

}
userDate.prompt = '起始时间';
userSearchDateFrom.datebox(userDate);
userDate.prompt = '结束时间'
userSearchDateTo.datebox(userDate);
/***********************查询区域********************/